import React, { useMemo, useState, useRef, useEffect } from 'react'
import domtoimage from 'dom-to-image'

import SvgIcon from '../common/svg-icon'
import videoStore from '../../store/video'

const canvas = document.createElement('canvas')
const canvasCtx = canvas.getContext('2d')
let once = 0

const ScreenshotBtn = () => {
  const ref = useRef()

  const [imgInfo, setImgInfo] = useState([])
  const [videoWrap, setVideoWrap] = useState()

  useEffect(() => {
    const videoWrap = document.getElementById('videoWrap')
    const { width, height, left, top } = videoWrap.getBoundingClientRect()
    setVideoWrap({ width, height, left, top })
  }, [ref])

  useMemo(() => {
    if (once > 0) {
      imgInfo.length > 0 ? drawSplitScreens() : download()
    } else {
      once++
    }
  }, [imgInfo])

  function getPlayingScreens() {
    const imgInfo = []
    for (const { player } of videoStore.playingScreens) {
      const { left, top, width, height } = player.video.getBoundingClientRect()
      imgInfo.push({ left, top, width, height })
    }
    setImgInfo(imgInfo)
  }

  // 绘制背景框
  async function drawBg() {
    const element = document.getElementById('videoWrap')
    const { width, height } = videoWrap
    const img = new Image()
    img.crossOrigin = 'anonymous'
    await domtoimage.toPng(element, { width, height }).then((url) => {
      img.src = url
    })
    if (img.complete) {
      canvas.setAttribute('width', width)
      canvas.setAttribute('height', height)
      canvasCtx.drawImage(img, 0, 0, width, height)
      getPlayingScreens()
    }
  }

  // 绘制分屏
  function drawSplitScreens() {
    for (const i in imgInfo) {
      const { width, height, left, top } = imgInfo[i]
      const video = videoStore.playingScreens[i].player.video
      const { videoHeight, videoWidth } = video
      // eslint-disable-next-line prettier/prettier
      const _videoHeight = width * videoHeight / videoWidth
      const _top = (height - _videoHeight) / 2
      canvasCtx.drawImage(
        video,
        0,
        0,
        videoWidth,
        videoHeight,
        left - videoWrap.left,
        top - videoWrap.top + _top,
        width,
        _videoHeight
      )
    }

    download()
  }

  function download() {
    const dataUrl = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.download = 'screen-shot.png'
    link.href = dataUrl
    link.click()
  }

  return (
    <div ref={ref} onClick={drawBg}>
      <SvgIcon icon="#iconshot" />
    </div>
  )
}

export default ScreenshotBtn
